package com.lyf.controller.user;

import com.lyf.pojo.AddressBook;
import com.lyf.result.Result;
import com.lyf.service.user.AddressBookService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@Api(tags = "用户端地址簿接口")
@RestController
@RequestMapping("/user/addressBook")
public class AddressBookController {
    @Autowired
    private AddressBookService addressBookService;

    @ApiOperation("新增地址")
    @PostMapping
    public Result save(@RequestBody AddressBook addressBook) {
        log.info("新增地址：{}",addressBook);
        addressBookService.save(addressBook);
        return Result.success();
    }

    @ApiOperation("根据id删除地址")
    @DeleteMapping
    public Result delete(Long id) {
        log.info("删除地址：{}",id);
        addressBookService.delete(id);
        return Result.success();
    }

    @ApiOperation("设置默认地址")
    @PutMapping("default")
    public Result setDefault(@RequestBody AddressBook addressBook) {
        log.info("设置默认地址：{}",addressBook);
        addressBookService.setDefault(addressBook);
        return Result.success();
    }

    @ApiOperation("修改地址")
    @PutMapping
    public Result update(@RequestBody AddressBook addressBook) {
        log.info("修改地址：{}",addressBook);
        addressBookService.update(addressBook);
        return Result.success();
    }

    @ApiOperation("查看当前用户的默认地址")
    @GetMapping("/default")
    public Result getDefault() {
        log.info("查看当前用户的默认地址");
        List<AddressBook> list = addressBookService.getDefault();
        AddressBook addressBook = null;
        // 获取当前用户的默认地址
        if (list != null && list.size() ==1 ){
            addressBook = list.get(0);
        }
        return Result.success(addressBook);
    }

    @ApiOperation("查看当前用户的地址簿")
    @GetMapping("/list")
    public Result list() {
        log.info("查看当前用户的地址簿");
        List<AddressBook> list = addressBookService.list();
        return Result.success(list);
    }

    @ApiOperation("根据id查询地址")
    @GetMapping("/{id}")
    public Result get(@PathVariable Long id) {
        log.info("查看当前用户的某个地址数据：{}",id);
        List<AddressBook> list = addressBookService.getById(id);
        if (list == null || list.size() != 1) {
            return Result.error("没有查询到数据");
        }
        AddressBook addressBook = list.get(0);
        return Result.success(addressBook);
    }
}
